package com.example.haiti.infrastructure.surveyor;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class questionnaire_Activity2 extends Activity {
	
    private Utils utilsHelper = null;
    private Cursor structureCursor = null;
    private int structureID;
	
	private EditText Edit_yearStructureBuilt  = null;    
    private EditText Edit_builderName= null;
    private Spinner spinner_Ownership = null;
    private Spinner spinner_ConstructionYears = null;  
    
    
    private static final int OWNERSHIP_ADAPTOR_ID = 0;
    private static final int CONSTRUCTION_YEARS_ADAPTOR_ID = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.questionnaire_layout_2);
                
        utilsHelper = new Utils(questionnaire_Activity2.this);      

        utilsHelper.openDatabase(); 

    	getStructure();       
   	       
        // Initializes view
        manageEditTextFields();
        initializeSpinners();
        setupNextButton();
                 
    } // end of the onCreate method
    
    @Override
    protected void onPause() {
        super.onPause();

        utilsHelper.closeDatabase();
    }
    
    @Override
    protected void onStop() {
      super.onStop();
       
    	utilsHelper.closeDatabase();
    }
    
    private void getStructure(){
    	// Get structure ID
        structureID = getIntent().getIntExtra("structureID", 1000); //Get structureID otherwise 1000      
        structureCursor = utilsHelper.getStructureCursor(structureID);	    	
    }
    
    private void manageEditTextFields(){
    	
    	// Declares the text input fields
	    Edit_yearStructureBuilt = (EditText) this.findViewById(R.id.editYearBuilt);     
	    Edit_builderName = (EditText) this.findViewById(R.id.EditBuilderName); 
         
        // Checks if data already exists
        String yearBuilt= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_YEAR_BUILT));
		String builderName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_BUILDER));

		// Sets the text of the input fields
	    Edit_yearStructureBuilt.setText(yearBuilt);
	    Edit_builderName.setText(builderName);
    }   
    
 private void initializeSpinners(){
    	
    	// Ownership Array Adapter
        ArrayAdapter<CharSequence> adapter_Ownership = ArrayAdapter.createFromResource(
        		this, R.array.OwnershipAnswers, android.R.layout.simple_spinner_item );
      			adapter_Ownership.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);

      			spinner_Ownership = (Spinner) findViewById( R.id.spinnerOwnership);
      			spinner_Ownership.setAdapter( adapter_Ownership );
      			
      		//  Sets the location of spinner to saved value if there is one\
      			int ownershipPosition = getArrayPosition(OWNERSHIP_ADAPTOR_ID);
      			spinner_Ownership.setSelection(ownershipPosition, true);
      			      			
       // Construction Years Array Adapter
       ArrayAdapter<CharSequence> adapter_ContstructionDuration = ArrayAdapter.createFromResource(
    		   	this, R.array.ConstructionYearsDuration, android.R.layout.simple_spinner_item );
       			adapter_ContstructionDuration.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);      		  
       	        
       			spinner_ConstructionYears = (Spinner) findViewById( R.id.SpinnerConstructionDuration);
       	        spinner_ConstructionYears.setAdapter( adapter_ContstructionDuration );
       	        
      		//  Sets the location of spinner to saved value if there is one
      			int constructionPosition = getArrayPosition(CONSTRUCTION_YEARS_ADAPTOR_ID);
       	        spinner_ConstructionYears.setSelection(constructionPosition,true);    	
    }
 
 	private int getArrayPosition(int spinnerType){
 		
 		int position=0;
 		
 		switch (spinnerType){
 		
 			case OWNERSHIP_ADAPTOR_ID:
 				
 				ArrayAdapter ownership_Adapter = (ArrayAdapter) spinner_Ownership.getAdapter();			
 	 			String ownershipValue= structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_OWNED));
 	 			position = ownership_Adapter.getPosition(ownershipValue);
 				
 				break;
 				
 			case CONSTRUCTION_YEARS_ADAPTOR_ID:
 				
 	 			ArrayAdapter construction_Adapter = (ArrayAdapter) spinner_ConstructionYears.getAdapter();
 	 			String constructionYearsValue = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_BUILD_DURATION));
 	 			position = construction_Adapter.getPosition(constructionYearsValue);
 				
 				break; 	
 				
 			default:				
 				break;
 			 		 		 		
 		}							
 		
 		return position;
 	}
   
    private void setupNextButton(){
    	 	
    	// Add Next button
        Button btnNextQuestions = (Button) findViewById(R.id.buttonNext);
        btnNextQuestions.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	
             // Defines strings input in by the user from Edit Text Fields
                String yearBuilt = Edit_yearStructureBuilt.getText().toString();
                String builderName = Edit_builderName.getText().toString();
                
             // Defines values input from Spinners
                String ownership = spinner_Ownership.getSelectedItem().toString();
                String constructionYears = spinner_ConstructionYears.getSelectedItem().toString();
                                                             
                String[][] databaseUpdates = {
                        {SqlHelper.COLUMN_STRUCTURE_OWNED, ownership},
                        {SqlHelper.COLUMN_STRUCTURE_YEAR_BUILT, yearBuilt},
                        {SqlHelper.COLUMN_STRUCTURE_BUILD_DURATION, constructionYears},
                        {SqlHelper.COLUMN_STRUCTURE_BUILDER, builderName}
                        };               
                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID );
               
                utilsHelper.startNextActivity(structureID, questionnaire_Activity3.class);
                
            }
        }); // End of  Next button click listener            
    }       
    
    // Back Button Pressed
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            utilsHelper.startNextActivity(structureID, questionnaire_Activity1.class);
        }
        return super.onKeyDown(keyCode, event);
    }
} 